package bookshop.controller.backend;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import bookshop.domain.Book;
import bookshop.domain.Category;
import bookshop.exception.ApplicationException;
import bookshop.exception.DataAccessException;
import bookshop.service.BookService;
import bookshop.service.CategoryService;
import bookshop.service.helper.BookQueryHelper;
import bookshop.service.impl.BookServiceImpl;
import bookshop.service.impl.CategoryServiceImpl;
import bookshop.utils.Page;

public class BookServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
	
		
		// 获得系统临时文件夹，不同的操作系统，以及不同JDK版本，临时文件夹的所在位置均不同，所以JDK提供了一个系统专用参数，来帮助我们获取该文件夹所在位置。
		// System.out.println(System.getProperty("java.io.tmpdir"));
		File tempFile = new File(System.getProperty("java.io.tmpdir"));
		// 我们目前使用fileUpload组件来进行混合有文件数据的表单提交信息的servlet端获取
		// (用这个库可以少花大量的时间，少写很多代码，但是需要掌握这个库一些概念，才能达到该效果）。
		// fileitem: 普通表单域和文件上传域均为fileitem.
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(4096); // 最大接收数量
		factory.setRepository(tempFile);// 接收的数据临时存放文件夹

		// 获取sfu是以上代码的最终目标，该组件能够套在httprequest,进行数据读取，并能对其内容分门别类，做好过滤工作，分出普通表单域和文件上传域。
		ServletFileUpload sfu = new ServletFileUpload(factory);
		sfu.setSizeMax(5000000); // 单个文件最大体积为5M.

		String act=null;
		List<FileItem> fileItems=null;
		if(ServletFileUpload.isMultipartContent(request)) //判断request是否是多段提交
		{
			try {
				
				fileItems=sfu.parseRequest(request);
				for(FileItem item:fileItems)
				{
					if(item.isFormField() && item.getFieldName().equals("act"))
                    {
                    	act=item.getString("utf-8");
                    	break;
                    } 					
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		else{
		    act=request.getParameter("act");
		}

		if ("input_book".equals(act)) {

			CategoryService ctgService = new CategoryServiceImpl();
			request.setAttribute("ctgs", ctgService.loadall());
			request.getRequestDispatcher("/jsps/backend/book/input_book.jsp")
					.forward(request, response);

		} else if ("regBook".equals(act)) {
			Book book=new Book();
			
			for(FileItem item:fileItems)
			{
				if(item.isFormField() && item.getFieldName().equals("bookcode"))
                	book.setBookCode(item.getString("utf-8"));
				else if(item.isFormField() && item.getFieldName().equals("bookname"))
					book.setBookName(item.getString("utf-8"));
				else if(item.isFormField() && item.getFieldName().equals("bookprice"))
					book.setBookPrice(Double.parseDouble(item.getString("utf-8")));
				else if(item.isFormField() && item.getFieldName().equals("bookauthor"))
					book.setBookAuthor(item.getString("utf-8"));
				else if(item.isFormField() && item.getFieldName().equals("bookpublisher"))
					book.setBookPublisher(item.getString("utf-8"));
				else if(item.isFormField() && item.getFieldName().equals("bookCtg"))
				{
					int bookCtg=Integer.parseInt(item.getString("utf-8"));
					Category ctg=new Category();
					ctg.setCtgId(bookCtg);			
					book.setCtg(ctg);
				}
				else if(item.isFormField() && item.getFieldName().equals("bookpubdate")){
					SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
					Date bookPubDate=null;
					try {
						bookPubDate=sdf.parse(item.getString("utf-8"));
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					book.setBookPubDate(bookPubDate);
				}
				else if(item.isFormField() && item.getFieldName().equals("bookdesc"))
					book.setBookDesc(item.getString("utf-8"));
				else if(!item.isFormField() && item.getFieldName().equals("bookimage")){
                      byte[] coverImg=new byte[(int)item.getSize()]; //测量该item所携带数据的大小，创建同等容量的byte[]来做存储准备。
                      item.getInputStream().read(coverImg, 0, (int)item.getSize());  
                      book.setBookImage(coverImg);
				}
				
			}

			BookService bookService = new BookServiceImpl();
			try {
				bookService.newBook(book);
				response.sendRedirect("bookMgr?act=qryloadall");
			} catch (ApplicationException e) {
				e.printStackTrace();
				CategoryService ctgService = new CategoryServiceImpl();
				request.setAttribute("errMsg", e.getMessage());   
				request.setAttribute("ctgs", ctgService.loadall());
				request.getRequestDispatcher("jsps/backend/book/input_book.jsp")
						.forward(request, response);
			}

		} else if("qryloadall".equals(act)){
		//设置一个查询参数存储容器
		BookQueryHelper helper=new BookQueryHelper();
		
		//根据情况，把提交过来的查询参数写入helper,以方便传给后台，进行记录的条件过滤。
		if(request.getParameter("qryBookCode")!=null && request.getParameter("qryBookCode").length()!=0)
		    helper.setQryBookCode(request.getParameter("qryBookCode"));
		
		if(request.getParameter("qryBookPubYear")!=null && request.getParameter("qryBookPubYear").length()!=0)
		    helper.setQryBookCode(request.getParameter("qryBookPubYear"));
		
		if(request.getParameter("qryBookName")!=null && request.getParameter("qryBookName").length()!=0)
		    helper.setQryBookName(request.getParameter("qryBookName"));
		
		if(request.getParameter("qryBookPublisher")!=null && request.getParameter("qryBookPublisher").length()!=0)
		    helper.setQryBookPublisher(request.getParameter("qryBookPublisher"));
		
		if(request.getParameter("qryBookPubYearLeft")!=null && request.getParameter("qryBookPubYearLeft").length()!=0)
			   helper.setQryBookPubYearLeft(request.getParameter("qryBookPubYearLeft"));
		
		if(request.getParameter("qryBookPubYearRight")!=null && request.getParameter("qryBookPubYearRight").length()!=0)
			   helper.setQryBookPubYearRight(request.getParameter("qryBookPubYearRight"));
			  
		
		if(request.getParameter("qryBookPriceLeft")!=null && request.getParameter("qryBookPriceLeft").length()!=0)
		   helper.setQryBookPriceLeft(Double.parseDouble(request.getParameter("qryBookPriceLeft")));
		  
		
		if(request.getParameter("qryBookPriceRight")!=null && request.getParameter("qryBookPriceRight").length()!=0)
			helper.setQryBookPriceRight(Double.parseDouble(request.getParameter("qryBookPriceRight")));
			
		
		if(request.getParameter("qryBookCtg")!=null && Integer.parseInt(request.getParameter("qryBookCtg"))>0)
		    helper.setQryBookCtg(Integer.parseInt(request.getParameter("qryBookCtg")));
		
		
		
		if(request.getParameter("PriceSequence")!=null)
			helper.setBookPriceSequence(request.getParameter("PriceSequence"));
		
		
		//创建页面对象,如果外界没有指定要第几页,默认就是第一页,如果有指定,比如 bookMgr?act=loadBooks&pageNo=3,则取第3页。
		Page page=new Page();
		if(request.getParameter("pageNo")!=null)
			page.setPageNo(Integer.parseInt(request.getParameter("pageNo")));
		
		BookService bookService=new BookServiceImpl();
		
		//helper未指定，也就是说，所有的属性为null, 则分页就是对所有记录的分页。
		//如果helper有指定属性，则分页，是基于组合查询基础上的分页。
        request.setAttribute("page",bookService.loadBooksByCondition(helper,page));
		
		CategoryService ctgs = new CategoryServiceImpl();
		request.setAttribute("ctgs", ctgs.loadall());
		request.getRequestDispatcher("jsps/backend/book/list_books.jsp").forward(request, response);
		
	}
		else if("showcover".equals(act))
	{
		String bookCode=request.getParameter("bookcode");
		
		BookService bookService=new BookServiceImpl();
		byte[] image=bookService.loadCover(bookCode);
		
		if(image==null || image.length==0)
		{
		  	//System.out.println(request.getRealPath("/"));
			String fileName=request.getRealPath("/")+"pics/backend/no_book_cover.jpg";
			File file=new File(fileName);
			FileInputStream fis=new FileInputStream(file);
			image=new byte[fis.available()];
			fis.read(image);
		}
		
		response.setContentType("image/jpeg");
		ServletOutputStream sos=response.getOutputStream();
		sos.write(image);
		sos.flush();
		sos.close();
		
	}else if("preModify".equals(act)){
		String bookCode = request.getParameter("bookcode");
		BookService bkService = new BookServiceImpl();
     	CategoryService ctgService = new CategoryServiceImpl();
		request.setAttribute("ctgs", ctgService.loadall());
		request.setAttribute("book", bkService.getBookByCode(bookCode));
		request.getRequestDispatcher("jsps/backend/book/update_book.jsp").forward(request, response);
	
	
	}else if("update".equals(act)){
		Book book=new Book();
		BookService bs = new BookServiceImpl();
		CategoryService ctgs = new CategoryServiceImpl();
		
		for(FileItem item:fileItems)
		{
			if(item.isFormField() && item.getFieldName().equals("bookcode"))
            	book.setBookCode(item.getString("utf-8"));
			else if(item.isFormField() && item.getFieldName().equals("bookname"))
				book.setBookName(item.getString("utf-8"));
			else if(item.isFormField() && item.getFieldName().equals("bookprice"))
				book.setBookPrice(Double.parseDouble(item.getString("utf-8")));
			else if(item.isFormField() && item.getFieldName().equals("bookauthor"))
				book.setBookAuthor(item.getString("utf-8"));
			else if(item.isFormField() && item.getFieldName().equals("bookMark"))
				book.setBookMark(Integer.parseInt(item.getString("utf-8")));
			else if(item.isFormField() && item.getFieldName().equals("bookpublisher"))
				book.setBookPublisher(item.getString("utf-8"));
			else if(item.isFormField() && item.getFieldName().equals("bookCtg"))
			{
				int bookCtg=Integer.parseInt(item.getString("utf-8"));
				Category ctg=new Category();
				ctg = ctgs.getCategoryById(bookCtg);
				book.setCtg(ctg);
			}
			else if(item.isFormField() && item.getFieldName().equals("bookpubdate")){
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
				Date bookPubDate=null;
				try {
					bookPubDate=sdf.parse(item.getString("utf-8"));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				book.setBookPubDate(bookPubDate);
			}
			else if(item.isFormField() && item.getFieldName().equals("bookdesc"))
				book.setBookDesc(item.getString("utf-8"));
			else if(!item.isFormField() && item.getFieldName().equals("bookimage")){
				  if(item.getSize()>0){
                  byte[] coverImg=new byte[(int)item.getSize()]; //测量该item所携带数据的大小，创建同等容量的byte[]来做存储准备。
                  item.getInputStream().read(coverImg, 0, (int)item.getSize());  
                  book.setBookImage(coverImg);
				  }else{
					  book.setBookImage(bs.loadCover(book.getBookCode()));
				  }
			}
			
		}
		
		try {
			bs.updateBook(book);
			response.sendRedirect("bookMgr?act=qryloadall");
		} catch (DataAccessException e) {
			e.printStackTrace();
			CategoryService ctgService = new CategoryServiceImpl();
			request.setAttribute("errMsg", e.getMessage());   
			request.setAttribute("ctgs", ctgService.loadall());
			request.getRequestDispatcher("jsps/backend/book/input_book.jsp")
					.forward(request, response);
		}

		
		
	}else if("remove".equals(act)){
		String bookCode = request.getParameter("bookcode");
		BookService bookService = new BookServiceImpl();
	    try {
			bookService.removeBook(bookCode);
			request.getSession().setAttribute("errMsg","编号为["+bookCode+"]的图书删除成功!");
		} catch (ApplicationException e) {
			e.printStackTrace();
			request.getSession().setAttribute("errMsg", e.getMessage());
		}
	    
	    response.sendRedirect("bookMgr?act=qryloadall");
	
	}
		
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

}
